#!/usr/bin/env python3
"""
SMS调试工具
用于在开发环境下查看Redis中存储的短信验证码
"""

import json
import time
from datetime import datetime


def print_sms_code_info(phone, code, expire_time=300, mode="development"):
    """
    在控制台打印格式化的短信验证码信息
    """
    console_data = {
        "type": "sms_code_generated",
        "phone": phone,
        "code": code,
        "expire_time": expire_time,
        "timestamp": time.time(),
        "readable_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "mode": mode
    }
    
    print("=" * 60)
    print("[SMS验证码信息]")
    print(json.dumps(console_data, ensure_ascii=False, indent=2))
    print("=" * 60)


def query_redis_sms_code(phone):
    """
    查询Redis中指定手机号的验证码
    """
    try:
        from utils.redis_client import redis_client
        
        code = redis_client.get_sms_code(phone)
        ttl = redis_client.get_sms_code_ttl(phone)
        exists = redis_client.check_sms_code_exists(phone)
        
        result = {
            "type": "sms_code_query",
            "phone": phone,
            "code": code,
            "exists": exists,
            "remaining_time": ttl if ttl > 0 else 0,
            "query_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "redis_available": redis_client.redis_available
        }
        
        print("=" * 60)
        print("[Redis验证码查询]")
        print(json.dumps(result, ensure_ascii=False, indent=2))
        print("=" * 60)
        
        return result
        
    except Exception as e:
        error_result = {
            "type": "sms_code_query_error",
            "phone": phone,
            "error": str(e),
            "query_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        
        print("=" * 60)
        print("[Redis验证码查询错误]")
        print(json.dumps(error_result, ensure_ascii=False, indent=2))
        print("=" * 60)
        
        return error_result


def list_all_sms_codes():
    """
    列出Redis中所有的短信验证码（仅开发环境使用）
    """
    try:
        from utils.redis_client import redis_client
        
        if not redis_client.redis_available:
            print("Redis不可用，无法查询验证码列表")
            return
            
        # 获取所有SMS验证码的key
        keys = redis_client.redis_client.keys("sms_code:*")
        
        codes_info = []
        for key in keys:
            phone = key.replace("sms_code:", "")
            code = redis_client.get_sms_code(phone)
            ttl = redis_client.get_sms_code_ttl(phone)
            
            codes_info.append({
                "phone": phone,
                "code": code,
                "remaining_time": ttl
            })
        
        result = {
            "type": "all_sms_codes",
            "total_count": len(codes_info),
            "codes": codes_info,
            "query_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        
        print("=" * 60)
        print("[所有短信验证码]")
        print(json.dumps(result, ensure_ascii=False, indent=2))
        print("=" * 60)
        
        return result
        
    except Exception as e:
        error_result = {
            "type": "all_sms_codes_error",
            "error": str(e),
            "query_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        
        print("=" * 60)
        print("[查询所有验证码错误]")
        print(json.dumps(error_result, ensure_ascii=False, indent=2))
        print("=" * 60)
        
        return error_result


if __name__ == "__main__":
    # 命令行工具使用示例
    import sys
    
    if len(sys.argv) < 2:
        print("使用方法:")
        print("python sms_debug_tools.py query <手机号>    # 查询指定手机号的验证码")
        print("python sms_debug_tools.py list              # 列出所有验证码")
        sys.exit(1)
    
    command = sys.argv[1]
    
    if command == "query" and len(sys.argv) >= 3:
        phone = sys.argv[2]
        query_redis_sms_code(phone)
    elif command == "list":
        list_all_sms_codes()
    else:
        print("未知命令") 